/**
 * Created by Administrator on 2017/7/18.
 */
let advanceDao = require('../mysql/advanceDao.js');
let mailDao = require('../mysql/mailDao.js');
let userDao = require('../mysql/userDao.js');
let chipDao = require('../mysql/chipDao.js');
let giftDao = require('../mysql/giftDao.js');
let timesDao = require('../mysql/timesDao.js');
let signInDao = require('../mysql/signInDao.js');
let msg = require('../util/msg.js');
let str = require('../util/str.js');
let util = require('../util/util.js');
let mailUtil = require('../util/mailUtil.js');
let variable = require('../data/variable.js');
let gameData = require('../util/gameData.js');

let mail = module.exports;

/**
 * 邮件列表
 * @param userId
 * @param cid
 * @param uuid
 */
mail.list = function (userId, cid, uuid) {
    mail.allList(userId, function (res) {
        let data = [];
        if (res) {
            data = res;
        }
        msg.send(cid, uuid, 'funcMailList', data);
    });
};
mail.allList = function (userId, cb) {
    let time = Math.floor(Date.now() / 1000);
    advanceDao.init().table('mail').wheres('userId', '=', userId).get(function (err, res) {
        if (err !== null) {
            cb(null);
            return false;
        }
        if (res.length == 0) {
            cb(null);
            return false;
        }
        for (let i in res) {
            res[i].time = time - res[i].time;
        }
        cb(res);
    });
};
/**
 * 单领邮件
 * @param userId
 * @param id
 * @param cid
 * @param uuid
 */
mail.take = function (userId, id, cid, uuid) {
    let mailModel = new mailDao();
    mailModel.inId(id, function (err, res) {
        if (!res) {
            msg.send(cid, uuid, 'error', {'api': 'funcMailTake', 'code': 10068});
            return false;
        }
        if (userId != res.res.userId) {
            msg.send(cid, uuid, 'error', {'api': 'funcMailTake', 'code': 10069});
            return false;
        }
        //let data = {'gold': res.res.gold, 'score': res.res.score, 'gem': res.res.gem};
        let save = false, coin = {}, chip = {};
        let texts = [];
        for (let i = 1; i <= 3; i++) {
            if (!res.res['attachment' + i] || res.res['amount' + i] <= 0) {
                continue;
            }
            save = true;
            if (res.res['attachment' + i] == 'gold' ||
                res.res['attachment' + i] == 'score' ||
                res.res['attachment' + i] == 'gem') {
                if (!coin[res.res['attachment' + i]]) {
                    coin[res.res['attachment' + i]] = 0;
                }
                coin[res.res['attachment' + i]] += res.res['amount' + i];
                //texts.push(res.res['amount' + i] + str[res.res['attachment' + i]]);
            } else {
                if (!chip[res.res['attachment' + i]]) {
                    chip[res.res['attachment' + i]] = 0;
                }
                chip[res.res['attachment' + i]] += res.res['amount' + i];
                //texts.push(res.res['amount' + i] + gameData.d.chip[res.res['attachment' + i]].name);
            }
        }
        if (save) {
            for (let i in coin) {
                texts.push(coin[i] + str[i]);
            }
            for (let i in chip) {
                texts.push(chip[i] + gameData.d.chip[i].name);
            }
            mail.toUser(userId, cid, uuid, coin);
            mail.toChip(userId, cid, uuid, chip);
            msg.send(cid, uuid, 'globalAlert', {'text': '收到了 ' + texts.join('，'), 'title': null});
            msg.send(cid, uuid, 'funcMailTake', {'id': id});
        }
        mailModel.delete(function () {
        });
    });
};

/**
 * 全领邮件
 * @param userId
 * @param cid
 * @param uuid
 */
mail.takeAll = function (userId, cid, uuid) {
    mail.allList(userId, function (list) {
        let save = false, coin = {}, chip = {};
        let texts = [];
        for (let k in list) {
            for (let i = 1; i <= 3; i++) {
                if (!list[k]['attachment' + i] || list[k]['amount' + i] <= 0) {
                    continue;
                }
                save = true;
                if (list[k]['attachment' + i] == 'gold' ||
                    list[k]['attachment' + i] == 'score' ||
                    list[k]['attachment' + i] == 'gem') {
                    if (!coin[list[k]['attachment' + i]]) {
                        coin[list[k]['attachment' + i]] = 0;
                    }
                    coin[list[k]['attachment' + i]] += list[k]['amount' + i];
                    //texts.push(list[k]['amount' + i] + str[list[k]['attachment' + i]]);
                } else {
                    if (!chip[list[k]['attachment' + i]]) {
                        chip[list[k]['attachment' + i]] = 0;
                    }
                    chip[list[k]['attachment' + i]] += list[k]['amount' + i];
                    //texts.push(list[k]['amount' + i] + gameData.d.chip[list[k]['attachment' + i]].name);
                }
            }
        }
        if (save) {
            for (let i in coin) {
                texts.push(coin[i] + str[i]);
            }
            for (let i in chip) {
                texts.push(chip[i] + gameData.d.chip[i].name);
            }
            mail.toUser(userId, cid, uuid, coin);
            mail.toChip(userId, cid, uuid, chip);
            msg.send(cid, uuid, 'globalAlert', {'text': '收到了 ' + texts.join('，'), 'title': null});
            msg.send(cid, uuid, 'funcMailTakeAll');
        }
        mail.deleteAll(userId);
    });
};
mail.deleteAll = function (userId) {
    advanceDao.init().table('mail').wheres('userId', '=', userId).delete(function () {
    });
};


mail.toUser = function (id, cid, uuid, data) {
    if (data.gold + data.score + data.gem <= 0) {
        return false;
    }
    let userModel = new userDao();
    userModel.inId(id, function (err2, res2) {
        if (!res2) {
            msg.send(cid, uuid, 'error', {'api': 'funcMailTake', 'code': 10062});
            return false;
        }
        let resultData = {};
        let save = false;
        for (let i in data) {
            if (data[i] <= 0) {
                continue;
            }
            let coin = res2.res[i] + data[i];
            resultData[i] = {'now': coin, 'add': data[i]};
            userModel.set(i, coin);
            save = true;
        }
        if (!save) {
            return false;
        }
        userModel.save(function (err3, res3) {
            if (!res3) {
                return false;
            }
            msg.send(cid, uuid, 'globalUserChange', resultData);
        });
    });
};

mail.toChip = function (id, cid, uuid, data) {
    let len = Object.keys(data).length;
    if (len <= 0) {
        return false;
    }
    let resultData = {}, i = 0;
    for (let k in data) {
        let chipModel = new chipDao();
        chipModel.inChipId(id, k, function (err, res) {
            chipModel.addNum(data[k]);
            chipModel.save(function (err1, res1) {
                i++;
                resultData[k] = {'now': chipModel.data.num, 'add': data[k]};
                if (i >= len) {
                    msg.send(cid, uuid, 'globalUserChange', resultData);
                }
            });
        });
    }
};

/**
 * 好友送礼
 * @param id
 * @param cid
 * @param uuid
 * @param data
 */
mail.giveGift = function (id, cid, uuid, data) {
    let date = new Date().Format("yyyy-MM-dd");
    advanceDao.init().table('gift').wheres('sourceId', '=', id).wheres('date', '=', date).count(function (err, res) {
        //if (err) {
        //    msg.send(cid, uuid, 'globalAlert', {'text': '发送失败', 'title': null});
        //    return false;
        //}
        if (res && res.num >= 30) {
            msg.send(cid, uuid, 'error', {'api': 'funcGiveGift', 'code': 10071});
            return false;
        }

        let giftModel = new giftDao();
        giftModel.inTargetToday(id, data.id, date, function (err1, res1) {
            //if (err1) {
            //    msg.send(cid, uuid, 'globalAlert', {'text': '发送失败', 'title': null});
            //    return false;
            //}
            if (res1) {
                msg.send(cid, uuid, 'error', {'api': 'funcGiveGift', 'code': 10073});
                //msg.send(cid, uuid, 'funcGiveGift', {'id': data.id, 'state': 2});
                return false;
            }
            giftModel.set('userId', data.id);
            giftModel.set('sourceId', id);
            giftModel.set('date', date);
            giftModel.save(function (err2, res2) {
                if (err2 != null) {
                    return false;
                }
                msg.send(cid, uuid, 'funcGiveGift', {'id': data.id, 'state': 1});
                let attachment = {};
                attachment.gold = 100;
                mailUtil.send(1, data.id, data.name, data.avatar, '好友送礼', attachment);
            });
        });
    });
};

mail.dailySignInBak = function (userId, cid, uuid) {
    let signInModel = new signInDao();
    signInModel.inId(userId, function (err, res) {
        if (!res) {
            return false;
        }
        let date = new Date();
        let dateN = new Date(res.res.date);
        let ymd = date.Format("yyyy-MM-dd");
        let ymdN = dateN.Format('yyyy-MM-dd');
        if (ymd == ymdN) {
            msg.send(cid, uuid, 'error', {'api': 'funcDailySignIn', 'code': 10072});
            return false;
        }
        if (parseInt(Math.abs(date - dateN) / 1000 / 60 / 60 / 24) > 1) {
            res.res.times = 0;
        }
        let nowTimes = res.res.times;
        let len = Object.keys(gameData.d.signIn).length;
        if (res.res.times >= len) {
            nowTimes = len - 1;
        }
        let coinAmount = gameData.d.signIn[nowTimes].coin;
        let coinType = gameData.d.signIn[nowTimes].type;
        let times = res.res.times + 1;
        //if (times >= gameData.d.signIn.length) {
        //    times = 0;
        //}
        signInModel.set('times', times);
        signInModel.set('date', date);
        signInModel.save(function () {
        });
        let userModel = new userDao();
        userModel.inId(userId, function (err2, res2) {
            if (!res2) {
                msg.send(cid, uuid, 'error', {'api': 'funcDailySignIn', 'code': 10062});
                return false;
            }
            let resultData = {};
            let coin = res2.res[coinType] + coinAmount;
            resultData[coinType] = {'now': coin, 'add': coinAmount};
            userModel.set(coinType, coin);
            userModel.save(function (err3, res3) {
                if (!res3) {
                    return false;
                }
                msg.send(cid, uuid, 'funcDailySignIn', {'times': times});
                msg.send(cid, uuid, 'globalUserChange', resultData);
                msg.send(cid, uuid, 'globalAlert', {'text': '签到领取了' + coinAmount + '金币', 'title': null});
            });
        });
    });
};


mail.dailySignIn = function (userId, cid, uuid) {
    let timesModel = new timesDao();
    timesModel.inId(userId, function (err, res) {
        if (!res) {
            return false;
        }
        if (res.res.signInState) {
            msg.send(cid, uuid, 'error', {'api': 'funcDailySignIn', 'code': 10072});
            return false;
        }
        let nowTimes = res.res.signIn;
        let len = Object.keys(gameData.d.signIn).length;
        if (res.res.signIn >= len) {
            nowTimes = len - 1;
        }
        let coinAmount = gameData.d.signIn[nowTimes].coin;
        let coinType = gameData.d.signIn[nowTimes].type;
        let times = res.res.signIn + 1;
        //if (times >= gameData.d.signIn.length) {
        //    times = 0;
        //}
        timesModel.set('signIn', times);
        timesModel.set('signInState', 1);
        timesModel.save(function () {
        });
        let userModel = new userDao();
        userModel.inId(userId, function (err2, res2) {
            if (!res2) {
                msg.send(cid, uuid, 'error', {'api': 'funcDailySignIn', 'code': 10062});
                return false;
            }
            let resultData = {};
            let coin = res2.res[coinType] + coinAmount;
            resultData[coinType] = {'now': coin, 'add': coinAmount};
            userModel.set(coinType, coin);
            userModel.save(function (err3, res3) {
                if (!res3) {
                    return false;
                }
                msg.send(cid, uuid, 'funcDailySignIn', {'times': times});
                msg.send(cid, uuid, 'globalUserChange', resultData);
                msg.send(cid, uuid, 'globalAlert', {'text': '签到领取了' + coinAmount + '金币', 'title': null});
            });
        });
    });
};


mail.onlineReward = function (userId, cid, uuid) {
    let timesModel = new timesDao();
    timesModel.inId(userId, function (err, res) {
        if (!gameData.d.onlineReward[timesModel.data.onlineNum]) {
            msg.send(cid, uuid, 'error', {'api': 'funcOnlineReward', 'code': 10083});
            return false;
        }
        let time = (Date.now() / 1000);
        let online = time - timesModel.data.onlineTime;
        let second = online + timesModel.data.online;
        if (second < (gameData.d.onlineReward[timesModel.data.onlineNum].minute * 60)) {
            msg.send(cid, uuid, 'error', {'api': 'funcOnlineReward', 'code': 10082});
            return false;
        }
        let onlineNum = timesModel.data.onlineNum + 1;
        let now = (Date.now() / 1000);
        let coinType = gameData.d.onlineReward[timesModel.data.onlineNum].type;
        let coinAmount = gameData.d.onlineReward[timesModel.data.onlineNum].coin;

        timesModel.set('onlineNum', onlineNum);
        timesModel.set('online', 0);
        timesModel.set('onlineTime', now);
        timesModel.save(function (err1, res1) {
            let result = {};
            if (gameData.d.onlineReward[onlineNum]) {
                result.online = (gameData.d.onlineReward[onlineNum].minute * 60);
            }
            msg.send(cid, uuid, 'funcOnlineReward', result);
        });

        if (coinType == 'gold' || coinType == 'gem' || coinType == 'score') {
            let userModel = new userDao();
            userModel.inId(userId, function (err2, res2) {
                let resultData = {};
                let coin = res2.res[coinType] + coinAmount;
                resultData[coinType] = {'now': coin, 'add': coinAmount};
                userModel.set(coinType, coin);
                userModel.save(function (err3, res3) {
                    msg.send(cid, uuid, 'globalUserChange', resultData);
                    msg.send(cid, uuid, 'globalAlert', {'text': '领取了在线奖励' + coinAmount + '金币', 'title': null});
                });
            });
        } else {
            let chipModel = new chipDao();
            chipModel.inChipId(userId, coinType, function (err2, res2) {
                let resultData = {};
                userModel.add(coinAmount);
                resultData[coinType] = {'now': userModel.data[coinType], 'add': coinAmount};
                userModel.save(function (err3, res3) {
                    msg.send(cid, uuid, 'globalUserChange', resultData);
                    msg.send(cid, uuid, 'globalAlert', {
                        'text': '领取了在线奖励' + coinAmount + gameData.d.chip[coinType].name,
                        'title': null
                    });
                });
            });
        }
    });
};